import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../config/const.dart';
import '../../../config/r.dart';
import '../controller.dart';

// 邮箱登录表单
class EmailLoginForm extends StatefulWidget {
  final Function(AuthMode) onSwitchAuthMode;

  // 使用邮箱登录
  final Function(String, String) loginWithEmailAction;

  // 三方登录
  final Function() thirdLoginAction;

  const EmailLoginForm({
    super.key,
    required this.onSwitchAuthMode,
    required this.loginWithEmailAction,
    required this.thirdLoginAction,
  });

  @override
  State<EmailLoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<EmailLoginForm> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _obscurePassword = true;

  void _submit() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    // 调用登录方法
    widget.loginWithEmailAction(
      _emailController.text.trim(),
      _passwordController.text.trim(),
    );
  }

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(milliseconds: 500), () {
      _emailController.text = "15820448983@163.com";
      _passwordController.text = "12345678";
    });
    // 自动弹出键盘
    return Form(
      key: _formKey,
      child: Column(
        children: [
          // Email Field
          TextFormField(
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            maxLength: emailMaxLength,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  color: const Color(0xFFEEEEEE).withOpacity(0.6),
                  fontSize: 14),
              labelText: local.email_address,
              prefixIcon: Image.asset(R.emailIcon, width: 18, height: 18),
              counterText: '',
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return local.please_enter_your_email_address;
              }
              if (!value.contains('@')) {
                return local.please_enter_valid_email_address;
              }
              return null;
            },
          ),
          SizedBox(height: 16.w),

          // Password Field
          TextFormField(
            controller: _passwordController,
            obscureText: _obscurePassword,
            maxLength: passwordMaxLength,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  color: const Color(0xFFEEEEEE).withOpacity(0.6),
                  fontSize: 14),
              labelText: local.password,
              prefixIcon: Image.asset(R.loginPwdIcon, width: 18, height: 18),
              suffixIcon: IconButton(
                icon: Icon(
                    _obscurePassword ? Icons.visibility : Icons.visibility_off),
                onPressed: () {
                  setState(() {
                    _obscurePassword = !_obscurePassword;
                  });
                },
              ),
              counterText: '', // Hide the character counter
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return local.please_enter_your_password;
              }
              if (value.length < passwordMinLength) {
                return local.enter_password_by_register(
                    passwordMinLength, passwordMaxLength);
              }
              return null;
            },
          ),
          SizedBox(height: 10.w),

          // Forgot Password
          Align(
            alignment: Alignment.centerRight,
            child: TextButton(
              onPressed: () {
                widget.onSwitchAuthMode(AuthMode.forgotPassword);
              },
              child: Text(
                local.forgot_password,
                style: TextStyle(
                    color: Colors.white.withOpacity(0.6), fontSize: 12),
              ),
            ),
          ),
          SizedBox(height: 24.w),

          // Login Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _submit,
              style: ElevatedButton.styleFrom(
                backgroundColor: LxCol.theme.withOpacity(0.8),
                padding: EdgeInsets.symmetric(vertical: 16.w),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: Text(local.email_login,
                  style: const TextStyle(fontSize: 16, color: Colors.white)),
            ),
          ),

          SizedBox(
            width: double.infinity,
            child: Wrap(
              spacing: 2.0.w, // 水平间距
              runSpacing: 0.0, // 垂直间距
              crossAxisAlignment: WrapCrossAlignment.center,
              alignment: WrapAlignment.start,
              children: [
                Text(
                  local.no_account,
                  style: TextStyle(
                      color: Colors.white.withOpacity(0.6), fontSize: 12),
                ),
                TextButton(
                  onPressed: () {
                    widget.onSwitchAuthMode(AuthMode.emailRegister);
                  },
                  child: Text(
                    local.register_account,
                    style: TextStyle(
                        color: Colors.white.withOpacity(0.6), fontSize: 12),
                  ),
                ),
              ],
            ),
          ),

          // Divider
          Row(
            children: [
              const Expanded(child: Divider()),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.w),
                child: Text(
                  local.or,
                  style: TextStyle(
                      color: Colors.white.withOpacity(0.6), fontSize: 14),
                ),
              ),
              const Expanded(child: Divider()),
            ],
          ),
          SizedBox(height: 16.w),

          // Third login
          Row(
            children: [
              // Google login button
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    widget.thirdLoginAction();
                  },
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.grey,
                    side: const BorderSide(color: Colors.grey),
                    padding: EdgeInsets.symmetric(vertical: 16.w),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Platform.isAndroid
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              R.googleLoginIcon,
                              width: 25,
                              height: 25,
                            ).colorFiltered(
                              color: Colors.white.withOpacity(0.6),
                            ),
                            SizedBox(width: 8.w),
                            Flexible(
                              child: Text(
                                local.google_login,
                                softWrap: true,
                                overflow: TextOverflow.visible,
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.white.withOpacity(0.6)),
                              ),
                            ),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              R.appleLoginIcon,
                              width: 25,
                              height: 25,
                            ).colorFiltered(
                              color: Colors.white.withOpacity(0.6),
                            ),
                            SizedBox(width: 8.w),
                            Flexible(
                              child: Text(
                                local.apple_login,
                                softWrap: true,
                                overflow: TextOverflow.visible,
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.white.withOpacity(0.6)),
                              ),
                            ),
                          ],
                        ),
                ),
              ),
              SizedBox(width: 16.w),
              // Phone login button
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    widget.onSwitchAuthMode(AuthMode.phoneLogin);
                  },
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.grey,
                    side: const BorderSide(color: Colors.grey),
                    padding: EdgeInsets.symmetric(vertical: 16.w),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(R.phoneIcon, width: 25, height: 25)
                          .colorFiltered(
                        color: Colors.white.withOpacity(0.6),
                      ),
                      SizedBox(width: 8.w),
                      Flexible(
                        child: Text(
                          local.phone_login,
                          softWrap: true,
                          overflow: TextOverflow.visible,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.white.withOpacity(0.6)),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
